<template>
  <div v-loading="loading">
    <div class="text-right mb-3" v-if="viewMode">
      <el-button @click="handlePrint">
        <i class="fa fa-fw fa-print"></i>
        打印
      </el-button>
      <el-button @click="handleExport" :loading="downloadLoading">
        <i class="fa fa-fw fa-download"></i>
        导出
      </el-button>
    </div>
    <table :id="printId" class="table text-center table-vertical-middle table-sm">
      <colgroup>
        <col width="25%" />
        <col width="5%" />
        <col width="21%" />
        <col width="14%" />
        <col width="14%" />
        <col width="21%" />
      </colgroup>
      <tbody>
        <tr class="bd-0">
          <td colspan="6">
            <h3 class="text-center">融资担保公司季度监管报表</h3>
          </td>
        </tr>
        <tr class="bd-0">
          <td colspan="6" class="text-right">表号：G7表</td>
        </tr>
        <tr class="bd-0">
          <td colspan="6" class="text-right">制表机关：中国银行保险监督管理委员会</td>
        </tr>
        <tr class="bd-0">
          <td colspan="6" class="text-right">数据单位：家、万元、倍、户、%</td>
        </tr>
        <tr class="bd-0">
          <td colspan="3" class="text-left">填报单位：{{ orgName }}</td>
          <td colspan="3" class="text-left">{{ dateLabel }}</td>
        </tr>
        <tr class="bd-1">
          <td rowspan="2">项目</td>
          <td rowspan="2">代码</td>
          <td>A</td>
          <td>B</td>
          <td>C</td>
          <td>D</td>
        </tr>
        <tr class="bd-1">
          <td>期初数</td>
          <td>本季度增加（发生额）</td>
          <td>本季度减少/解除 （发生额）</td>
          <td>期末数</td>
        </tr>
        <tr class="bd-1" v-for="item in editData" :key="item.b">
          <td class="text-left" :class="item.style">{{ item.a }}</td>
          <td>{{ item.b }}</td>
          <td :class="item.notedit || item.c1 ? '' : tdClass">
            <span v-if="viewMode || item.notedit || item.c1">{{ item.c1 || item.c }}</span>
            <el-input
              v-else
              class="text-center"
              type="number"
              @input="setNotEditNumber"
              v-model="item.c"
            ></el-input>
          </td>
          <td :class="item.notedit || item.d1 ? '' : tdClass">
            <span v-if="viewMode || item.notedit || item.d1">{{ item.d1 || item.d }}</span>
            <el-input
              v-else
              class="text-center"
              type="number"
              @input="setNotEditNumber"
              v-model="item.d"
            ></el-input>
          </td>
          <td :class="item.notedit || item.e1 ? '' : tdClass">
            <span v-if="viewMode || item.notedit || item.e1">{{ item.e1 || item.e }}</span>
            <el-input
              v-else
              class="text-center"
              type="number"
              @input="setNotEditNumber"
              v-model="item.e"
            ></el-input>
          </td>
          <td :class="item.notedit || item.f1 ? '' : tdClass">
            <span v-if="viewMode || item.notedit || item.f1">
              {{ item.f1 || item.f }}{{ item.f ? item.funit : '' }}
            </span>
            <el-input
              v-else
              class="text-center"
              type="number"
              @input="setNotEditNumber"
              v-model="item.f"
            ></el-input>
          </td>
        </tr>
        <tr class="bd-0">
          <td colspan="2" class="text-left">{{ tableInfo.res_person || user.realName }}</td>
          <td colspan="2" class="text-left">
            填表人及联系方式：{{ tableInfo.submit_person_name || user.realName }}
            {{ tableInfo.phone_number || user.phoneNumber }}
          </td>
          <td colspan="2" class="text-left">报出日期：{{ createDate }}</td>
        </tr>
        <tr class="bd-0">
          <td colspan="6" class="text-left">
            <pre class="report-desc">{{ reportDesc }}</pre>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="mb-5 text-center" v-if="!viewMode">
      <el-button :loading="saveLoading" class="btn-long" type="primary" @click="save">
        保存
      </el-button>

      <el-button class="mr-2 btn-long" :loading="saveLoading" @click="beforeClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumQuarter } from '@/credit/views/city/reportCity/manage/quarter/minix'
import { excelTableExport, domHasClass, printWithIframe } from '@vimi/utils-tool'

export default {
  components: {},
  props: {
    queryYear: {
      type: Number,
      required: true,
    },
    queryQuarter: {
      type: Number,
      required: true,
    },
    viewMode: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      tableData: [
        {
          a: '本省（区、市）融资担保法人机构数量',
          b: '701',
          c: '',
          d: '',
          e: '',
          f: '',
          notedit: true,
        },
        {
          a: '其中：国有控股融资担保机构数量',
          b: '702',
          c: '',
          d: '',
          e: '',
          f: '',
          style: 'text-indent-1',
        },
        {
          a: '民营及外资融资担保机构数量',
          b: '703',
          c: '',
          d: '',
          e: '',
          f: '',
          style: 'text-indent-2',
        },
        { a: '实收资本', b: '704', c: '', d: '', e: '', f: '' },
        {
          a: '净资产（扣除对其他融资担保公司和再担保公司的股权投资）',
          b: '705',
          c: '',
          d: '',
          e: '',
          f: '',
          c1: '-',
          d1: '-',
          e1: '-',
        },
        { a: '融资担保金额', b: '706', c: '', d: '', e: '', f: '', notedit: true },
        {
          a: '其中：直接融资担保金额',
          b: '707',
          c: '',
          d: '',
          e: '',
          f: '',
          style: 'text-indent-1',
        },
        {
          a: '其中：小微企业担保',
          b: '708',
          c: '',
          d: '',
          e: '',
          f: '',
          d1: '-',
          e1: '-',
          style: 'text-indent-2',
        },
        {
          a: '农户及新型农业经营主体担保',
          b: '709',
          c: '',
          d: '',
          e: '',
          f: '',
          d1: '-',
          e1: '-',
          style: 'text-indent-3',
        },
        {
          a: '战略性新兴产业担保',
          b: '710',
          c: '',
          d: '',
          e: '',
          f: '',
          d1: '-',
          e1: '-',
          style: 'text-indent-3',
        },
        {
          a: '其中：国有控股融资担保机构',
          b: '711',
          c: '',
          d: '',
          e: '',
          f: '',
          d1: '-',
          e1: '-',
          style: 'text-indent-2',
        },
        {
          a: '民营及外资融资担保机构',
          b: '712',
          c: '',
          d: '',
          e: '',
          f: '',
          d1: '-',
          e1: '-',
          style: 'text-indent-3',
        },
        { a: '融资再担保金额', b: '713', c: '', d: '', e: '', f: '', style: 'text-indent-1' },
        {
          a: '融资担保在保余额放大倍数',
          b: '714',
          c: '',
          d: '',
          e: '',
          f: '',
          c1: '-',
          d1: '-',
          e1: '-',
          notedit: true,
        },
        { a: '融资担保户数', b: '715', c: '', d: '', e: '', f: '', notedit: true },
        {
          a: '其中：直接融资担保户数',
          b: '716',
          c: '',
          d: '',
          e: '',
          f: '',
          style: 'text-indent-1',
        },
        {
          a: '其中：小微企业担保',
          b: '717',
          c: '',
          d: '',
          e: '',
          f: '',
          d1: '-',
          e1: '-',
          style: 'text-indent-2',
        },
        {
          a: '农户及新型农业经营主体担保',
          b: '718',
          c: '',
          d: '',
          e: '',
          f: '',
          d1: '-',
          e1: '-',
          style: 'text-indent-3',
        },
        {
          a: '战略性新兴产业担保',
          b: '719',
          c: '',
          d: '',
          e: '',
          f: '',
          d1: '-',
          e1: '-',
          style: 'text-indent-3',
        },
        { a: '融资再担保户数', b: '720', c: '', d: '', e: '', f: '', style: 'text-indent-1' },
        { a: '直接融资担保代偿金额', b: '721', c: '', d: '', e: '', f: '' },
        {
          a: '当季直接融资担保代偿率',
          b: '722',
          c: '',
          d: '',
          e: '',
          f: '',
          c1: '-',
          d1: '-',
          e1: '-',
          notedit: true,
        },
        {
          a: '本年累计直接融资担保年化综合收入',
          b: '723',
          c: '',
          d: '',
          e: '',
          f: '',
          c1: '-',
          d1: '-',
          e1: '-',
        },
        {
          a: '本年累计直接融资担保新增金额',
          b: '724',
          c: '',
          d: '',
          e: '',
          f: '',
          c1: '-',
          d1: '-',
          e1: '-',
        },
        {
          a: '本年直接融资担保年化综合费率',
          b: '725',
          c: '',
          d: '',
          e: '',
          f: '',
          c1: '-',
          d1: '-',
          e1: '-',
          funit: '%',
          notedit: true,
        },
      ],
      reportDesc: `填报说明：
1.本表由各省、自治区、直辖市融资担保公司监督管理部门填报。
2.本表统计范围为在本省（区、市）持有融资担保业务经营许可证的融资担保法人机构，本省（区、市）融资担保法人机构在省（区、市）内外设立的分支机构数据需汇总至法人机构后统一填报。
3.外币数据须按报告期末最后一天国家外汇管理局公布的基准汇价折合为人民币数据进行汇总。
4.填列的金额按四舍五入保留整数；报表中划横线部分不需填列。
5.小微企业、农户及新型农业经营主体、战略性新兴产业主体交叉的，可以重复统计。
6.本报表为季报，报送时间为季后25日前。
7.校验关系：[A]+[B]-[C]=[D]，[702]+[703]=[701]，[707]+[713]=[706]，[711]+[712]=[707]，[706D]÷[705D]=[714D]，[716]+[720]=[715]，[721B]÷[707C]=[722D]，[723D]÷[724D]=[725D]。`,

      downloadLoading: false,
      saveLoading: false,
      editData: [],
      tableName: 'report_quarter',
      loading: false,
      params: {
        'quarter_type.eq': 5,
        subKey: 'report_quarter_detail_county.report_quarter_id',
      },
      order: {},
      tableInfo: {},
    }
  },
  computed: {
    ...mapGetters(['org', 'user', 'clientId']),
    orgName() {
      return this.org.orgName
    },
    dateLabel() {
      return `${this.queryYear}第${enumQuarter[this.queryQuarter]}季度`
    },
    printId() {
      return `g7-${this.queryYear}-${this.queryQuarter}`
    },
    tdClass() {
      return this.viewMode ? '' : 'input-td'
    },
    createDate() {
      return this.$utils.dateFormat(this.tableInfo.update_time || new Date(), 'yyyy年MM月dd日')
    },
  },
  watch: {
    printId: {
      handler: function () {
        this.params['service_id.eq'] = this.clientId
        this.params['year_number.eq'] = this.queryYear
        this.params['quarter_number.eq'] = this.queryQuarter
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    setNotEditNumber() {
      const sum723D = (this.editData.find(item => +item.b === 723) || {}).f || 0
      const sum724D = (this.editData.find(item => +item.b === 724) || {}).f || 0
      this.$set(
        this.editData[24],
        'f',
        sum724D ? Math.round((sum723D / sum724D) * 10000) / 100 : ''
      )

      // const sum707 = this.sumKey([711, 712])
      // this.$set(this.editData[6], 'c', sum707.c)
      // this.$set(this.editData[6], 'd', sum707.d)
      // this.$set(this.editData[6], 'e', sum707.e)
      // this.$set(this.editData[6], 'f', sum707.f)

      const sum721B = (this.editData.find(item => +item.b === 721) || {}).d || 0
      const sum707C = (this.editData.find(item => +item.b === 707) || {}).e || 0
      this.$set(
        this.editData[21],
        'f',
        sum707C ? Math.round((sum721B / sum707C) * 10000) / 100 : ''
      )

      const sum706 = this.sumKey([707, 713])
      this.$set(this.editData[5], 'c', sum706.c)
      this.$set(this.editData[5], 'd', sum706.d)
      this.$set(this.editData[5], 'e', sum706.e)
      this.$set(this.editData[5], 'f', sum706.f)

      const sum705D = (this.editData.find(item => +item.b === 705) || {}).f || 0
      const sum706D = (this.editData.find(item => +item.b === 706) || {}).f || 0
      this.$set(this.editData[13], 'f', sum705D ? Math.round((sum706D / sum705D) * 100) / 100 : '')

      const sum715 = this.sumKey([716, 720])
      this.$set(this.editData[14], 'c', sum715.c)
      this.$set(this.editData[14], 'd', sum715.d)
      this.$set(this.editData[14], 'e', sum715.e)
      this.$set(this.editData[14], 'f', sum715.f)

      const sum701 = this.sumKey([702, 703])
      this.$set(this.editData[0], 'c', sum701.c)
      this.$set(this.editData[0], 'd', sum701.d)
      this.$set(this.editData[0], 'e', sum701.e)
      this.$set(this.editData[0], 'f', sum701.f)
    },
    sumKey(arr) {
      let sum1 = 0
      let sum2 = 0
      let sum3 = 0
      let sum4 = 0
      arr.forEach(order => {
        const addItem = this.editData.find(item => +item.b === order) || {}
        sum1 += +addItem.c || 0
        sum2 += +addItem.d || 0
        sum3 += +addItem.e || 0
        sum4 += +addItem.f || 0
      })
      return {
        c: sum1 || '',
        d: sum2 || '',
        e: sum3 || '',
        f: sum4 || '',
      }
    },
    getData() {
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          this.tableInfo = res?.data?.[0] ?? {}
          const data = this.tableInfo.report_quarter_detail_county || []
          this.tableData = this.tableData.map(item => {
            const row = data.find(d => d.dimension_key === item.b) || {}
            item.c = +row.quarter_begin_funds || ''
            item.d = +row.quarter_add_funds || ''
            item.e = +row.quarter_reduce_funds || ''
            item.f = +row.quarter_end_funds || ''

            item.id = row.id
            return item
          })
          this.editData = this.tableData.map(item => {
            return { ...item }
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    save() {
      const masterData = {
        quarter_type: 5,
        report_no: 'G7表',
        report_name: '融资担保公司季度监管报表',
        res_person: this.user.realName,
        phone_number: this.user.phoneNumber,
        year_number: this.queryYear,
        quarter_number: this.queryQuarter,
        service_id: this.clientId,
        submit_person_name: this.user.realName,
      }
      if (this.tableInfo.report_quarter_id) {
        masterData.report_quarter_id = this.tableInfo.report_quarter_id
      }
      const slaveData = this.editData.map(item => {
        const data = {
          quarter_begin_funds: item.c || 0,
          quarter_add_funds: item.d || 0,
          quarter_reduce_funds: item.e || 0,
          quarter_end_funds: item.f || 0,
          order_num: item.b,
          dimension_key: item.b,
          dimension_key_name: item.a,
        }
        if (this.tableInfo.report_quarter_id) {
          data.report_quarter_id = this.tableInfo.report_quarter_id
          data.id = item.id
        }
        return data
      })
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: this.tableName,
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'report_quarter_detail_county',
      }
      this.saveLoading = true
      if (this.tableInfo.report_quarter_id) {
        this.$api
          .relatedUpdate(this.$serviceName, formData)
          .then(() => {
            this.$message.success('保存成功')
            this.$emit('success', true)
            this.getData()
            this.beforeClose()
          })
          .catch(() => {
            this.$message.error('保存失败，请重试！！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.$api
          .relatedBatch(this.$serviceName, formData)
          .then(() => {
            this.$message.success('保存成功')
            this.$emit('success', true)
            this.getData()
            this.beforeClose()
          })
          .catch(() => {
            this.$message.error('保存失败，请重试！！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      }
    },
    beforeClose() {
      this.editData = this.tableData.map(item => {
        return { ...item }
      })
      this.$emit('close', false)
    },
    handlePrint() {
      printWithIframe(document.getElementById(this.printId))
    },

    handleExport() {
      const borderAllThin = {
        left: { style: 'thin' },
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
      }
      const borderAllNone = {
        left: { style: 'none' },
        top: { style: 'none' },
        right: { style: 'none' },
        bottom: { style: 'none' },
      }

      this.downloadLoading = true
      excelTableExport(this.printId, '融资担保公司季度监管报表', {
        styles: {
          border: borderAllNone,
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        cellStyles: {
          A1: {
            font: {
              sz: 24,
              name: '方正小标宋简体',
            },
          },
          A34: {
            alignment: {
              vertical: 'top',
              wrapText: true,
            },
          },
          A7: {
            border: borderAllThin,
          },
        },
        cols: [
          { wch: 40.63 },
          { wch: 4.0 },
          { wch: 34.5 },
          { wch: 24.0 },
          { wch: 24.0 },
          { wch: 34.5 },
        ],
        rows: {
          0: { hpx: 48 },
          33: { hpx: 180 },
        },
        cellHandler({ value, tr, td }) {
          const style = {}

          if (domHasClass(tr, 'bd-1')) {
            style.border = borderAllThin
          } else if (domHasClass(tr, 'bd-0')) {
            style.border = borderAllNone
          }

          if (domHasClass(td, 'text-right')) {
            style.alignment = { horizontal: 'bottom' }
          } else if (domHasClass(td, 'text-left')) {
            style.alignment = { horizontal: 'top' }
          }

          const { className = '' } = td
          const indent = /text-indent-(\d+)/.exec(className)
          if (indent) {
            value = `${' '.repeat(+(indent[1] || 0) * 8)}${value}`
          }

          return { value, style }
        },
      }).finally(() => {
        this.downloadLoading = false
      })
    },
  },
}
</script>

<style lang="scss" scoped>
$indents: 1, 2, 3;
@each $i in $indents {
  .text-indent-#{$i} {
    text-indent: $i * 2rem;
  }
}

.report-desc {
  text-align: left;
  font-size: 1rem;
  white-space: pre-wrap;
  font-family: 'Microsoft Yahei', '\5FAE\8F6F\96C5\9ED1', Helvetica, Arial, sans-serif;
}

.bd-0 > td {
  border: none;
}

.bd-1 > td {
  border: 1px solid $border-color;
}
.input-td {
  background: #ffffee;
}
</style>
